#!/bin/bash

source /home/shell/util.sh

printInfo "====================="
lsb_release -a
printInfo "====================="

# 环境检测
firewall-must-run
mysql_file=`curl -sL https://dev.mysql.com/downloads/repo/apt/|grep href|grep deb|perl -pe "s/.*file=(.*)&.*/\1/g"`;
# 安装源
# wget https://dev.mysql.com/get/mysql-apt-config_0.8.16-1_all.deb && dpkg -i mysql-apt-config_0.8.16-1_all.deb
dpkg-install-fromurl https://dev.mysql.com/get/${mysql_file}
rm -rf mysql-apt-config_0.8.16-1_all.deb
apt update

# 安装mysql-server
apt install -y mysql-server libmysqlclient-dev expect 

# 推荐配置
printInfo "应用自定义配置……"
cp -f /home/shell/support/my.cnf /etc/mysql/mysql.conf.d/mysqld.cnf

# 设置mysql自启动
systemctl enable mysql.service
systemctl restart mysql.service

# 设置参数
read -p "请输入mysql root密码[123456]：" mysql_passwd
mysql_passwd=${mysql_passwd:-"123456"};

# 改密码
printInfo "修改root密码";
mysqladmin -u root password $mysql_passwd

expect <<EOF
    spawn mysql_config_editor set --login-path=local --host=localhost --user=root --password
    expect {
        "password" {send "$mysql_passwd\n";exp_continue}
        "exists" {send "y\n";interact}
    }
EOF

# root账户授权
# mysql --login-path=local -e "use mysql;update user set host='localhost' where user='root';FLUSH PRIVILEGES;GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';FLUSH PRIVILEGES;"
# 授权root system_user权限
# mysql --login-path=local -e "GRANT system_user on *.* to 'root'@'localhost';FLUSH PRIVILEGES;"
# 创建dev_user用户
mysql --login-path=local -e "CREATE USER 'dev_user'@'%' IDENTIFIED WITH mysql_native_password BY '$mysql_passwd';GRANT ALL PRIVILEGES ON *.* TO 'dev_user'@'%';FLUSH PRIVILEGES;"
# 设置权限
mysql --login-path=local -e "UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='dev_user';FLUSH PRIVILEGES;"

systemctl restart mysql.service
# 防火墙设置
firewall-addservice mysql

# 清理
rm -rf /etc/apt/sources.list.d/mysql.list
apt update

# mysql信息

printInfo "================================================mysql-server================================================"
printInfo "地址：$host_addr:3306"
printInfo "root密码：$mysql_passwd"
printInfo "dev_user密码：$mysql_passwd"
printInfo "生效配置：/etc/mysql/mysql.conf.d/mysqld.cnf"
echo -e "`cat /etc/mysql/mysql.conf.d/mysqld.cnf|grep -v "#"|grep -e '.*=.*'`"
printInfo "================================================mysql-server================================================"